<style>
  .picImg {
    width: 40px;
    height: 40px;
  }
</style>
<template>
  <div class="app-container">
    <!--&lt;!&ndash; 查询和其他操作 &ndash;&gt;-->
    <div class="filter-container">

      <el-button class="filter-item" type="primary" icon="el-icon-edit"
                 @click="handleAdd">新增
      </el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-upload"
                 @click="handleExport">批量上传代理人信息
      </el-button>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row
              :header-cell-style="{background:'#92D3FF',color:'#fff'}">
      <el-table-column align="center" min-width="80" label="类型" prop="type">
        <template slot-scope="scope">
          <el-tag>{{{"0":"个人","1":"企业"}[scope.row.type]}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" min-width="100" label="代理人姓名" prop="agentName"/>
      <el-table-column align="center" min-width="100" label="代理人编码" prop="agentNo"/>
      <el-table-column align="center" min-width="150" label="代理人身份证号" prop="agentID"/>
      <el-table-column align="center" min-width="120" label="收款账号" prop="account"/>
      <el-table-column align="center" min-width="120" label="账号名称" prop="accountName"/>
      <el-table-column align="center" min-width="100" label="所属银行名称" prop="bankName"/>
      <!--<el-table-column align="center" min-width="100" label="开户联行号" prop="interBankNo"/>-->
      <el-table-column align="center" min-width="120" label="联系人姓名" prop="linkMan"/>
      <el-table-column align="center" min-width="100" label="联系人手机号" prop="mobile"/>
      <el-table-column align="center" min-width="150" label="住址" prop="address"/>
      <el-table-column align="center" label="操作" width="220" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini"
                     @click="handleEdit(scope.row)">修改
          </el-button>
          <!--<el-button type="danger" size="mini"-->
                     <!--@click="doDelete(scope.row)">删除-->
          <!--</el-button>-->
          <el-popover
            placement="top"
            width="200"
            trigger="manual"
            :ref="'popover-' + scope.row.agentNo">
            <p>确定删除该数据吗？</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="$refs[`popover-` + scope.row.agentNo].doClose()">取消</el-button>
              <el-button type="primary" size="mini" @click="doDelete(scope.row)">确定</el-button>
            </div>
            <el-button type="danger" size="mini" slot="reference" @click="$refs[`popover-` + scope.row.agentNo].doShow()">删除</el-button>
          </el-popover>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize"
                @pagination="getList"/>
    <!-- 分配订单对话框 -->
    <el-dialog :visible.sync="editDialogVisible" :title="textMap[dialogStatus]" :close-on-click-modal="false">
      <el-form ref="editForm" :model="editForm" status-icon label-position="left"
               label-width="100px" style="width: 400px; margin-left:50px;">
        <el-form-item label="请选择类型：">
          <el-radio-group v-model="editForm.type" :disabled="dialogStatus != 'create'" @change="typeChange">
            <el-radio :label="1">公司</el-radio>
            <el-radio :label="0">个人</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <!--个人-->
      <el-form ref="editForm" :rules="editFormRules" :model="editForm" status-icon label-position="left"
               label-width="130px" style="width: 400px; margin-left:50px;" v-if="editForm.type == 0">
        <el-form-item label="代理人姓名" prop="agentName">
          <el-input v-model="editForm.agentName"/>
        </el-form-item>
        <el-form-item label="代理人编码" prop="agentNo">
          <el-input v-model="editForm.agentNo" auto-complete="off" :disabled="this.bool"/>
        </el-form-item>
        <el-form-item label="代理人身份证号" prop="agentID">
          <el-input v-model="editForm.agentID" auto-complete="off"/>
        </el-form-item>
        <el-form-item label="收款账号" prop="account">
          <el-input v-model="editForm.account" auto-complete="off"/>
        </el-form-item>
        <el-form-item label="账号名称" prop="accountName">
          <el-input v-model="editForm.accountName" auto-complete="off"/>
        </el-form-item>
        <el-form-item label="银行名称" prop="bankName">
          <el-select :disabled="true" @change="bankNameChange" v-model="editForm.bankCode" placeholder="请选择">
            <el-option
              v-for="item in banks"
              :key="item.bankCode"
              :label="item.bankName"
              :value="item.bankCode"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!--<el-form-item label="开户联行号">
          <el-select v-model="editForm.interBankNo" placeholder="请选择">
            <el-option
              v-for="item in unionnos"
              :key="item.interBankNo"
              :label="item.interBankNo"
              :value="item.interBankNo"
            >
            </el-option>
          </el-select>
        </el-form-item>-->
        <!--<el-form-item label="所属银行代码" prop="bankCode">-->
          <!--<el-input v-model="editForm.bankCode" auto-complete="off"/>-->
        <!--</el-form-item>-->
        <!--<el-form-item label="开户联行号" prop="interBankNo">-->
          <!--<el-input v-model="editForm.interBankNo" auto-complete="off"/>-->
        <!--</el-form-item>-->
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editForm.mobile" auto-complete="off"/>
        </el-form-item>
        <el-form-item label="住址" prop="address">
          <el-input v-model="editForm.address" auto-complete="off"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="editForm.type == 0">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="doCreate">确定</el-button>
        <el-button v-else type="primary" @click="doEdit">确定</el-button>
      </div>

      <!--公司-->
      <el-form ref="editForm" :rules="editFormRules" :model="editForm" status-icon label-position="left"
               label-width="130px" style="width: 400px; margin-left:50px;" v-if="editForm.type == 1">
        <el-form-item label="企业名称" prop="agentName">
          <el-input v-model="editForm.agentName"/>
        </el-form-item>
        <el-form-item label="统一信用代码" prop="agentNo">
          <el-input v-model="editForm.agentNo" auto-complete="off" :disabled="this.bool"/>
        </el-form-item>
        <!--<el-form-item label="代理人身份证号" prop="agentID">
          <el-input v-model="editForm.agentID" auto-complete="off"/>
        </el-form-item>-->
        <el-form-item label="账户名称" prop="accountName">
          <el-input v-model="editForm.accountName" auto-complete="off"/>
        </el-form-item>
        <el-form-item label="收款账号" prop="account">
          <el-input @change="bankNameChange" v-model="editForm.account" auto-complete="off"/>
        </el-form-item>
        <el-form-item label="银行名称" prop="bankName">
          <el-select :disabled="true" v-model="editForm.bankCode" placeholder="请选择">
            <el-option
              v-for="item in banks"
              :key="item.bankCode"
              :label="item.bankName"
              :value="item.bankCode"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属银行名称" prop="interBankNo">
          <el-input readonly="readonly" v-model="editForm.bankName" auto-complete="off" placeholder="请选择" @click.native="getUnioLs()"/>
          <!--<el-select v-model="editForm.interBankNo" placeholder="请选择" filterable>
            <el-option
              v-for="item in unionnos"
              :key="item.interBankNo"
              :label="item.bankName"
              :value="item.interBankNo"
            >
            </el-option>
          </el-select>-->
        </el-form-item>
        <!--<el-form-item label="所属银行代码" prop="bankCode">-->
        <!--<el-input v-model="editForm.bankCode" auto-complete="off"/>-->
        <!--</el-form-item>-->
        <!--<el-form-item label="开户联行号" prop="interBankNo">-->
        <!--<el-input v-model="editForm.interBankNo" auto-complete="off"/>-->
        <!--</el-form-item>-->
        <el-form-item label="联系人姓名" prop="linkMan">
          <el-input v-model="editForm.linkMan" auto-complete="off"/>
        </el-form-item>
        <el-form-item label="联系人手机号" prop="mobile">
          <el-input v-model="editForm.mobile" auto-complete="off"/>
        </el-form-item>
        <el-form-item label="住址" prop="address">
          <el-input v-model="editForm.address" auto-complete="off"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="editForm.type == 1">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="doCreate">确定</el-button>
        <el-button v-else type="primary" @click="doEdit">确定</el-button>
      </div>

    </el-dialog>
    <!--上传代理人信息-->
    <el-dialog :visible.sync="exportDialogVisible1" title="批量上传代理人信息" :close-on-click-modal="false">
      <el-form ref="editForm" :rules="editFormRules" :model="editForm" status-icon label-position="left"
               label-width="100px" style="width: 400px;">
        <el-form-item label="请选择:" prop="type">
          <el-radio-group v-model="editForm.type">
            <el-radio :label="0">个人</el-radio>
            <el-radio :label="1">公司</el-radio>
          </el-radio-group>
        </el-form-item>
        <!--<el-form-item label="开户银行名称" prop="m">
          <el-input v-model="editForm.m" auto-complete="off" placeholder="开户银行名称" style="width:250px;"/>
        </el-form-item>-->
      </el-form>
      <el-upload
        class="upload-demo"
        ref="upload"
        action="string"
        :before-upload="beforeUploadFile"
        :http-request="doUpload"
        :file-list="fileList"
        :limit="1"
        name="filename"
        :auto-upload="false">
        <el-button size="small" plain>选择文件</el-button>
        <div slot="tip" class="el-upload__tip">只能上传xlsx(Excel2007)文件，且不超过10M</div>
        <!--<el-button slot="trigger" size="small" type="primary">选取文件</el-button>-->
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button style="margin-left: 10px;" size="small" type="success" @click="exportDialogVisible1=false">取消
        </el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" @click="$refs.upload.submit()">确定
        </el-button>
      </div>
    </el-dialog>

    <!--支行弹窗-->
    <el-dialog :visible.sync="UnionDialogVisible" title="选择开户银行名称" :close-on-click-modal="false">
      <div class="filter-container">
        <el-form :inline="true" status-icon label-position="left" class="demo-form-inline"
                 label-width="100px" style="width: 100%; margin-left:50px;">
          <el-form-item label="开户银行名称" prop="account">
            <el-input auto-complete="off" v-model="editForm1.interBankName" placeholder="开户银行名称" style="width:400px" />
          </el-form-item>
          <el-form-item>
            <el-button class="filter-item" type="primary" @click="queryUnio">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table v-loading="unionnosLoading" :data="unionnos" element-loading-text="正在查询中。。。" border fit highlight-current-row
                :header-cell-style="{background:'#92D3FF',color:'#fff'}">
        <el-table-column align="left" min-width="100" label="开户银行名称" prop="bankName"/>
        <el-table-column align="center" label="操作" width="200" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button type="primary" size="mini"
                       @click="choose(scope.row)">选择
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total1>0" :total="total1" :page.sync="editForm1.pageNum" :limit.sync="editForm1.pageSize"
                  @pagination="getUnionnos"/>
    </el-dialog>

  </div>
</template>

<script>
  import {doGet, doPost, doFile} from '@/api'
  import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

  const FETCH_PAGE = 'agentman.html'
  const FETCH_URL = {
    LIST: `${FETCH_PAGE}?op=list`,
    CREATE: `${FETCH_PAGE}?op=add`,
    IMPORT: `${FETCH_PAGE}?op=batchadd`,
    EDIT: `${FETCH_PAGE}?op=chg`,
    DELETE: `${FETCH_PAGE}?op=del`,
  }

  export default {
    name: 'bank',
      al : '',
      pageNum: '',
      pageSize: '',
    components: {Pagination},
    filters: {},
    data() {
      let accountValidate = (rule, value, callback) => {
        if (value && value.length >= 3) {
          let code = value.substring(0, 3)
          let flag = this.banks.some(item => {
            return item.bankCode == code
          })
          if (!flag) {
            callback(new Error('账号有误，请重新输入'));
          } else {
            this.editForm.bankCode = code
            callback()
          }
        } else {
          this.editForm.bankCode = undefined
          callback()
        }
      }
      return {
        list: [],
        total: 0,
          total1: 0,
        listLoading: true,
        listQuery: {
            pageNum: 1,
            pageSize: 20,
        },
        bool:false,
        editForm: {
          agentName: undefined,
          agentNo: undefined,
          agentID: undefined,
          account: undefined,
          accountName: undefined,
          bankCode: undefined,
          interBankNo: undefined,
          mobile: undefined,
          address: undefined,
          type: undefined,
        },
        editFormRules: {
          agentName: [{required: true, message: '代理人姓名不可为空', trigger: 'blur'}],
          agentNo: [{required: true, message: '代理人编码不可为空', trigger: 'blur'}],
          account: [{required: true, message: '收款账号不可为空', trigger: 'blur'},
                    {validator: accountValidate, trigger: 'change'}],
          accountName: [{required: true, message: '账号名称不可为空', trigger: 'blur'}],
          bankCode: [{required: true, message: '所属银行代码不可为空', trigger: 'blur'}],
          interBankNo: [{required: true, message: '所属银行名称不可为空', trigger: 'blur'}],
        },
        editDialogVisible: false,
        exportDialogVisible1: false,
        dialogStatus: undefined,
        textMap: {
          update: '编辑',
          create: '创建'
        },
        editIndex: undefined,
        fileList: [],
        banks:[],
        unionnos:[],
          unionnosLoading: true,
          UnionDialogVisible: false,
          editForm1: {
              pageNum: 1,
              pageSize: 20,
              bankCode: undefined,
              interBankName: undefined
          },
      }
    },
    created() {
      this.getList()
      this.getBanks()
    },
    methods: {
      getBanks() {
        doGet("bank.html?op=list",{}).then(response => {
          this.banks = response.rows
        }).catch((error) => {
          this.banks = []
        })
      },
        getUnionnos(subankCode, flag) {
            if (typeof(subankCode) == 'string') {
                this.pageNum = 1
                this.pageSize = 20
            } else {
                this.pageNum = subankCode.page
                this.pageSize = subankCode.limit
            }
            this.editForm1 = {
                pageNum: this.pageNum,
                pageSize: this.pageSize,
                bankCode: this.al,
                bankName: this.editForm1.interBankName,
                interBankNo: this.editForm.interBankNo,
                flag: flag
                // bankName: this.editForm.interBankNo
            }
            this.UnionDialogVisible = true
            this.unionnosLoading = true
            doGet('unionno.html?op=list', this.editForm1).then(response => {
                this.unionnos = response.rows
                this.total1 = response.data.totalcount
                this.unionnosLoading = false
            }).catch(() => {
                this.unionnos = []
                this.total1 = 0
                this.unionnosLoading = false
            })
        },
      bankNameChange(bankCode) {
          this.al = bankCode.substring(0, 3)
          var flag = '1';
          this.getUnionnos(this.al, flag)
        this.editForm.interBankNo = undefined
      },
      getList() {
        this.listLoading = true
        doGet(FETCH_URL.LIST,this.listQuery).then(response => {
          this.list = response.rows
          this.total = response.data.totalcount
          this.listLoading = false
        }).catch((error) => {
          console.log(JSON.stringify(error))
          this.list = []
          this.total = 0
          this.listLoading = false
        })
      },
      handleAdd() {
        this.editForm = {
          agentName: undefined,
          agentNo: undefined,
          agentID: undefined,
          account: undefined,
          accountName: undefined,
          bankCode: undefined,
          interBankNo: this.unionnos.interBankNo,
          mobile: undefined,
          address: undefined,
          type: 1,
        },
        this.editDialogVisible = true
        this.bool=false
        this.dialogStatus = 'create'
        this.$nextTick(() => {
          this.$refs['editForm'].clearValidate()
        })
      },
      doEdit() {
        this.$refs['editForm'].validate(valid => {
          if (valid) {
            let sendData = {
              ...this.editForm,
              type: this.editForm.type,
            }
            doGet(FETCH_URL.EDIT, sendData)
              .then(response => {
                this.getList()
                this.editDialogVisible = false
                this.list[this.editIndex] = this.editForm
                this.$notify.success({
                  title: '成功',
                  message: '修改代理人信息成功'
                })
              })
              .catch(response => {
                this.$notify.error({
                  title: '失败',
                  message: response.message
                })
              })
          }
        })
      },
      doCreate() {
        this.$refs['editForm'].validate(valid => {
          if (valid) {
            let sendData = {
              ...this.editForm,
            }
            doGet(FETCH_URL.CREATE, sendData)
              .then(response => {
                this.getList()
                this.editDialogVisible = false
                this.$notify.success({
                  title: '成功',
                  message: '添加代理人信息成功'
                })
              })
              .catch(response => {
                this.$notify.error({
                  title: '失败',
                  message: response.message
                })
              })
          }
        })
      },
      doDelete(row) {
        doGet(FETCH_URL.DELETE, {agentNo: row.agentNo})
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '删除代理人信息成功'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
            this.total--
            this.$refs[`popover-` + row.agentNo].doClose()
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.message
            })
          })
      },
      handleEdit(row) {
        this.editForm = Object.assign({}, row)
        this.editIndex = this.list.indexOf(row)
        this.getUnionnos(row.bankCode)
        this.bool=true
        this.dialogStatus = 'update'
        this.editDialogVisible = true
        this.$nextTick(() => {
          this.$refs['editForm'].clearValidate()
        })
      },
      handleExport(value) {
        this.editForm = {
            type: 0
        }
        this.exportDialogVisible1 = true
      },
      beforeUploadFile(file) {
        console.log('before upload')
        console.log(file)
        let extension = file.name.substring(file.name.lastIndexOf('.')+1)
        let size = file.size / 1024 / 1024
        if(extension !== 'xlsx'&&extension !== 'xls') {
          this.$notify.warning({
            title: '警告',
            message: `只能上传Excel（即后缀是.xlsx或.xls）的文件`
          });
          return false
        }
        // if(size > 10) {
        //   this.$notify.warning({
        //     title: '警告',
        //     message: `文件大小不得超过10M`
        //   });
        // }
      },
      doUpload(param) {
        let fd = new FormData()
        fd.append('filename', param.file)//传文件\
        fd.append('type', this.editForm.type)//传文件\
        doFile('agentman.html?op=batchadd', fd).then((res)=> {
          this.getList()
          this.exportDialogVisible1 = false
          this.$notify.success({
            title: '成功',
            message: '上传成功'
          })
        }).catch(response => {
          this.$notify.error({
            title: '失败',
            message: response.message
          })
        })
      },

      typeChange() {
        Object.keys(this.editForm).forEach(item => {
          if (item != 'type') {
            this.editForm[item] = undefined
          }
        })
        this.$refs['editForm'].clearValidate()
      },
        /**查询银行名称*/
        queryUnio() {
            this.UnionDialogVisible = true
            this.pageNum = this.pageNum
            this.pageSize = this.pageSize
            this.getUnionnos(this.al, '2')
        },
        getUnioLs() {
        if(this.al == null){
            alert('请选择填写收款账号')
          } else {
            this.UnionDialogVisible = true
            this.pageNum = this.pageNum
            this.pageSize = this.pageSize
            this.getUnionnos(this.al, '1')
          }
        },
        /** 选择分行*/
        choose(row) {
            this.editForm.interBankNo = row.interBankNo
            this.editForm.bankName = row.bankName
            this.editForm1.interBankName = row.bankName
            this.UnionDialogVisible = false
        },
    }
  }
</script>
